package litegame

import (
	"fmt"
	"net/http"
)

// 登录凭证
type WechatAccessToken struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
	BaseErrRet
}

const _wxGetAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"

func getWxAccessToken(appid, secret string) (*WechatAccessToken, error) {
	err, httpStatus, resp := httpGet(fmt.Sprintf(_wxGetAccessTokenUrl, appid, secret))
	if err != nil {
		return nil, err
	}
	if httpStatus != http.StatusOK {
		return nil, fmt.Errorf("getWxAccessToken失败 httpStatus=%d", httpStatus)
	}
	retWxStruct := &WechatAccessToken{}
	err = json.Unmarshal(resp, &retWxStruct)
	if err != nil {
		return nil, fmt.Errorf("getWxAccessToken解析失败 err=%s", err)
	}
	if retWxStruct.Errcode != 0 {
		return nil, fmt.Errorf("getWxAccessTokenError code=%d,msg=%s", retWxStruct.Errcode, retWxStruct.Errmsg)
	}
	return retWxStruct, nil
}
